import React, { useState, useEffect } from 'react';
import { useEditorStore } from '../store/useEditorStore';
import { UserSettings, EditorTheme } from '../types';
import { 
  Settings as SettingsIcon, 
  Palette, 
  Type, 
  Save, 
  RotateCcw, 
  Monitor, 
  Sun, 
  Moon, 
  Keyboard,
  Clock,
  Check,
  X
} from 'lucide-react';
import { toast } from 'sonner';

const Settings: React.FC = () => {
  const { settings, updateSettings } = useEditorStore();
  const [localSettings, setLocalSettings] = useState<UserSettings>(settings);
  const [hasChanges, setHasChanges] = useState(false);

  // 监听设置变化
  useEffect(() => {
    const isChanged = JSON.stringify(localSettings) !== JSON.stringify(settings);
    setHasChanges(isChanged);
  }, [localSettings, settings]);

  // 更新本地设置
  const updateLocalSetting = <K extends keyof UserSettings>(key: K, value: UserSettings[K]) => {
    setLocalSettings(prev => ({ ...prev, [key]: value }));
  };

  // 保存设置
  const handleSaveSettings = () => {
    updateSettings(localSettings);
    setHasChanges(false);
    toast.success('设置已保存');
  };

  // 重置设置
  const handleResetSettings = () => {
    const confirmed = window.confirm('确定要重置所有设置为默认值吗？');
    if (confirmed) {
      setLocalSettings(settings);
      setHasChanges(false);
      toast.success('设置已重置');
    }
  };

  // 获取主题图标
  const getThemeIcon = (theme: EditorTheme) => {
    switch (theme) {
      case 'light': return <Sun className="w-4 h-4" />;
      case 'dark': return <Moon className="w-4 h-4" />;
      case 'auto': return <Monitor className="w-4 h-4" />;
      default: return <Monitor className="w-4 h-4" />;
    }
  };

  const settingSections = [
    {
      title: '主题设置',
      icon: Palette,
      items: [
        {
          label: '编辑器主题',
          description: '选择编辑器的外观主题',
          component: (
            <div className="flex space-x-2">
              {(['light', 'dark', 'auto'] as EditorTheme[]).map((theme) => (
                <button
                  key={theme}
                  onClick={() => updateLocalSetting('theme', theme)}
                  className={`flex items-center px-3 py-2 rounded border transition-colors ${
                    localSettings.theme === theme
                      ? 'border-blue-500 bg-blue-50 text-blue-700 dark:bg-blue-900 dark:text-blue-300'
                      : 'border-gray-300 hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-800'
                  }`}
                >
                  {getThemeIcon(theme)}
                  <span className="ml-2 text-sm">
                    {theme === 'light' ? '浅色' : theme === 'dark' ? '深色' : '自动'}
                  </span>
                </button>
              ))}
            </div>
          )
        }
      ]
    },
    {
      title: '编辑器设置',
      icon: Type,
      items: [
        {
          label: '字体大小',
          description: '编辑器中文本的字体大小（像素）',
          component: (
            <input
              type="number"
              min="10"
              max="24"
              value={localSettings.fontSize}
              onChange={(e) => updateLocalSetting('fontSize', parseInt(e.target.value))}
              className="w-20 px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-800"
            />
          )
        },
        {
          label: 'Tab宽度',
          description: 'Tab键对应的空格数量',
          component: (
            <input
              type="number"
              min="2"
              max="8"
              value={localSettings.tabSize}
              onChange={(e) => updateLocalSetting('tabSize', parseInt(e.target.value))}
              className="w-20 px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-800"
            />
          )
        },
        {
          label: '自动换行',
          description: '当行内容超出编辑器宽度时自动换行',
          component: (
            <button
              onClick={() => updateLocalSetting('wordWrap', !localSettings.wordWrap)}
              className={`flex items-center px-3 py-2 rounded border transition-colors ${
                localSettings.wordWrap
                  ? 'border-green-500 bg-green-50 text-green-700 dark:bg-green-900 dark:text-green-300'
                  : 'border-gray-300 hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-800'
              }`}
            >
              {localSettings.wordWrap ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}
              <span className="ml-2 text-sm">{localSettings.wordWrap ? '已启用' : '已禁用'}</span>
            </button>
          )
        },
        {
          label: '显示行号',
          description: '在编辑器左侧显示行号',
          component: (
            <button
              onClick={() => updateLocalSetting('showLineNumbers', !localSettings.showLineNumbers)}
              className={`flex items-center px-3 py-2 rounded border transition-colors ${
                localSettings.showLineNumbers
                  ? 'border-green-500 bg-green-50 text-green-700 dark:bg-green-900 dark:text-green-300'
                  : 'border-gray-300 hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-800'
              }`}
            >
              {localSettings.showLineNumbers ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}
              <span className="ml-2 text-sm">{localSettings.showLineNumbers ? '已显示' : '已隐藏'}</span>
            </button>
          )
        },
        {
          label: '显示小地图',
          description: '在编辑器右侧显示代码小地图',
          component: (
            <button
              onClick={() => updateLocalSetting('showMinimap', !localSettings.showMinimap)}
              className={`flex items-center px-3 py-2 rounded border transition-colors ${
                localSettings.showMinimap
                  ? 'border-green-500 bg-green-50 text-green-700 dark:bg-green-900 dark:text-green-300'
                  : 'border-gray-300 hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-800'
              }`}
            >
              {localSettings.showMinimap ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}
              <span className="ml-2 text-sm">{localSettings.showMinimap ? '已显示' : '已隐藏'}</span>
            </button>
          )
        }
      ]
    },
    {
      title: '自动保存设置',
      icon: Clock,
      items: [
        {
          label: '启用自动保存',
          description: '定期自动保存编辑器内容到本地存储',
          component: (
            <button
              onClick={() => updateLocalSetting('autoSave', !localSettings.autoSave)}
              className={`flex items-center px-3 py-2 rounded border transition-colors ${
                localSettings.autoSave
                  ? 'border-green-500 bg-green-50 text-green-700 dark:bg-green-900 dark:text-green-300'
                  : 'border-gray-300 hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-800'
              }`}
            >
              {localSettings.autoSave ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}
              <span className="ml-2 text-sm">{localSettings.autoSave ? '已启用' : '已禁用'}</span>
            </button>
          )
        },
        {
          label: '自动保存间隔',
          description: '自动保存的时间间隔（秒）',
          component: (
            <div className="flex items-center space-x-2">
              <input
                type="number"
                min="5"
                max="300"
                value={localSettings.autoSaveInterval}
                onChange={(e) => updateLocalSetting('autoSaveInterval', parseInt(e.target.value))}
                disabled={!localSettings.autoSave}
                className="w-20 px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed dark:border-gray-600 dark:bg-gray-800"
              />
              <span className="text-sm text-gray-500">秒</span>
            </div>
          )
        }
      ]
    },
    {
      title: '快捷键',
      icon: Keyboard,
      items: [
        {
          label: '常用快捷键',
          description: '编辑器中的常用快捷键组合',
          component: (
            <div className="space-y-2 text-sm">
              <div className="flex justify-between items-center py-1">
                <span>保存文件</span>
                <kbd className="px-2 py-1 bg-gray-100 dark:bg-gray-700 rounded text-xs font-mono">Ctrl + S</kbd>
              </div>
              <div className="flex justify-between items-center py-1">
                <span>格式化代码</span>
                <kbd className="px-2 py-1 bg-gray-100 dark:bg-gray-700 rounded text-xs font-mono">Ctrl + Shift + F</kbd>
              </div>
              <div className="flex justify-between items-center py-1">
                <span>验证YAML</span>
                <kbd className="px-2 py-1 bg-gray-100 dark:bg-gray-700 rounded text-xs font-mono">Ctrl + Shift + V</kbd>
              </div>
              <div className="flex justify-between items-center py-1">
                <span>新建文件</span>
                <kbd className="px-2 py-1 bg-gray-100 dark:bg-gray-700 rounded text-xs font-mono">Ctrl + N</kbd>
              </div>
              <div className="flex justify-between items-center py-1">
                <span>打开文件</span>
                <kbd className="px-2 py-1 bg-gray-100 dark:bg-gray-700 rounded text-xs font-mono">Ctrl + O</kbd>
              </div>
            </div>
          )
        }
      ]
    }
  ];

  return (
    <div className="p-6 h-full flex flex-col">
      <div className="flex-shrink-0">
        <h1 className="text-2xl font-bold mb-6 flex items-center">
          <SettingsIcon className="w-6 h-6 mr-2" />
          设置
        </h1>
        
        {/* 操作按钮 */}
        <div className="mb-6 flex space-x-4">
          <button
            onClick={handleSaveSettings}
            disabled={!hasChanges}
            className={`flex items-center px-4 py-2 rounded transition-colors ${
              hasChanges
                ? 'bg-blue-600 text-white hover:bg-blue-700'
                : 'bg-gray-300 text-gray-500 cursor-not-allowed'
            }`}
          >
            <Save className="w-4 h-4 mr-2" />
            保存设置
          </button>
          <button
            onClick={handleResetSettings}
            className="flex items-center px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700 transition-colors"
          >
            <RotateCcw className="w-4 h-4 mr-2" />
            重置设置
          </button>
        </div>
        
        {hasChanges && (
          <div className="mb-6 p-3 bg-yellow-50 border border-yellow-200 rounded">
            <p className="text-yellow-800 text-sm">您有未保存的设置更改</p>
          </div>
        )}
      </div>
      
      {/* 设置内容 */}
      <div className="flex-1 overflow-auto">
        <div className="space-y-8">
          {settingSections.map((section, sectionIndex) => {
            const SectionIcon = section.icon;
            return (
              <div key={sectionIndex} className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                <h2 className="text-lg font-semibold mb-4 flex items-center">
                  <SectionIcon className="w-5 h-5 mr-2" />
                  {section.title}
                </h2>
                <div className="space-y-6">
                  {section.items.map((item, itemIndex) => (
                    <div key={itemIndex} className="flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-2 sm:space-y-0">
                      <div className="flex-1">
                        <h3 className="font-medium text-gray-900 dark:text-gray-100">{item.label}</h3>
                        <p className="text-sm text-gray-500 dark:text-gray-400">{item.description}</p>
                      </div>
                      <div className="flex-shrink-0">
                        {item.component}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

export default Settings;